﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.Office.Server.UserProfiles;
using System.Linq;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Salary_Advance_Form : LayoutsPageBase
    {

        SPHelper obj = new SPHelper();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string TicketNo;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string AdvanceDetails;

        public static string lstGuid { get; set; }
        public string camlQry;
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;

        public static string AdvRequestNo;

        public static int wfOrder = 0;

        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        string[] buttonVisibilty = new string[5];

        Label EmpName; Label EmpID; Label Division; Label Department; Label Designation; Label MobNo;

        SPListItem oItem = null;
        SPListItemCollection oItemColl = null;
        SPQuery qry;

        public static SPFieldUserValue fldSubmittedFor = null;

        #endregion

        public Salary_Advance_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Salary Advance Forms";
            TaskLstName = "Salary Advance Tasks";
            CmntsLstName = "Salary Advance Comments";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";
            AdvanceDetails = "Advance Details";

        }

        #region "User control manipulation"
        /// <summary>
        /// Get user control controls using find control method 
        /// </summary>
        private void GetUserControls()
        {
            EmpName = userInfo.FindControl("lblEmpName") as Label;
            EmpID = userInfo.FindControl("lblEmpID") as Label;
            Division = userInfo.FindControl("lblDivision") as Label;
            Department = userInfo.FindControl("lblDepartment") as Label;
            Designation = userInfo.FindControl("lblDesignation") as Label;
            MobNo = userInfo.FindControl("lblMobNo") as Label;
        }

        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            dtpDate.SelectedDate = DateTime.Today;

            try
            {
                Mode = Request.QueryString["Mode"];
                dtpDate.SelectedDate = DateTime.Today;
                GetUserControls();

                if (Mode == "New")
                {
                    ClearControls();
                    if (rdBtn.SelectedIndex == 1)
                        GetReqEmpInfo();
                    else
                        GetPersonnelActionForm();
                }


                if (!IsPostBack)
                {
                    ImgUser.ImageUrl = demandVoucherclass.GetUserProfilePictureURL(CurrentUser);
                    LblCommentsUserName.Text = CurrentUser;
                    if (Mode == "Edit" || Mode == "View")
                    {
                        FormApprovalLoad(); if (Mode == "View") InvisibleButtons();
                    }
                    else if (Mode == "New")
                    {
                        txtAdvance.Attributes.Add("onFocus", "ClearValues();");
                        txtInstalment.Attributes.Add("onFocus", "ClearValue();");

                        FirstLoadofForm();
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Salary Advance Form" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            txtInstalment.TextChanged += new EventHandler(txtInstalment_TextChanged);
        }

        protected void txtInstalment_TextChanged(object sender, EventArgs e)
        {
            double adv = Convert.ToDouble(txtAdvance.Text);
            double insTime = Convert.ToDouble(txtInstalment.Text);
            double pm = adv / insTime;
            txtDeduction.Text = Convert.ToString(Math.Round(pm, 2));
            dtStDate.ClearSelection();
            dtStDate.SelectedDate = DateTime.Today.AddMonths(1);


            dtEndDate.ClearSelection();
            if (insTime == 1)
            {
                dtEndDate.SelectedDate = DateTime.Today.AddMonths(1);
            }
            else
            {
                dtEndDate.SelectedDate = DateTime.Today.AddMonths(Convert.ToInt32(insTime));
            }

            double os = 0;
            if (!string.IsNullOrEmpty(txtOS.Text))
                os = Convert.ToDouble(txtAdvance.Text) + Convert.ToDouble(txtOS.Text);
            else
                os = Convert.ToDouble(txtAdvance.Text);

            txtTotOS.Text = Convert.ToString(os);
        }

        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        private void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);
                    if (string.IsNullOrEmpty(getDocRefNumber[0]) && string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: HR Request form" + " :: " + "Parent" + " :: " + "FirstLoadofForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }
                    ReLoadDetails();
                    //ControlsReadOnly();
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Function to bind data after the Form gets submitted.
        /// </summary>
        /// <param name="SiteURL"></param>

        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                string RefNo = Convert.ToString(Request.Params["RefID"]);

                camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + RefNo + "</Value></Eq></Where>";
                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {
                    lblSalAdvReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtpDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                    Label lblFormID = userInfo.FindControl("lblFormID") as Label;
                    lblFormID.Text = lstDatas.ParentList.ID.ToString();

                    Label lblreferenceNumber = AdvComments.FindControl("lblReferenceNumber") as Label;
                    Label lblSiteUrl = AdvComments.FindControl("lblSiteUrl") as Label;
                    Label lblfrmListName = AdvComments.FindControl("lblfrmListName") as Label;
                    Label lbldocumentypesList = AdvComments.FindControl("lbldocumentTypes") as Label;
                    Label lblCommentsList = AdvComments.FindControl("lblCommentsList") as Label;
                    Label lblTaskList = AdvComments.FindControl("lblTaskList") as Label;

                    lblTaskList.Text = TaskLstName;
                    lblCommentsList.Text = CmntsLstName;
                    lblfrmListName.Text = MainLstName;
                    lbldocumentypesList.Text = DocumentTypesList;
                    lblreferenceNumber.Text = lblSalAdvReqNo.Text;
                    lblSiteUrl.Text = SiteURL;

                    submittedfor = Convert.ToString(lstDatas["SubmittedFor"]);
                    SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
                    fldSubmittedFor = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
                    submittedfor = fldUser.LookupValue;

                    pnlSec.Enabled = false;

                    if (Convert.ToString(lstDatas["OnBehalfof"]) == "Yes")
                    {
                        rdBtn.SelectedIndex = 1;
                        pnlReqEmpInf.Visible = true;
                        SetValuestoOnBehalfof(lstDatas);
                    }

                    else
                    {
                        rdBtn.SelectedIndex = 0;
                    }

                    string user = Convert.ToString(lstDatas["SubmittedFor"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["DateofEmployment"])))
                        dtDOE.SelectedDate = Convert.ToDateTime(lstDatas["DateofEmployment"]);

                    txtBasicSalary.Text = Convert.ToString(lstDatas["BasicSalary"]);
                    txtAdvance.Text = Convert.ToString(lstDatas["AdvanceAmount"]); txtAdvance.ReadOnly = true;
                    txtInstalment.Text = Convert.ToString(lstDatas["Instalment"]); txtInstalment.ReadOnly = true;
                    txtDeduction.Text = Convert.ToString(lstDatas["DeductionAmount"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["StartsOn"])))
                        dtStDate.SelectedDate = Convert.ToDateTime(lstDatas["StartsOn"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["EndsOn"])))
                        dtEndDate.SelectedDate = Convert.ToDateTime(lstDatas["EndsOn"]);

                    txtOS.Text = Convert.ToString(lstDatas["OSAmount"]);
                    txtTotOS.Text = Convert.ToString(lstDatas["TtlOSAmount"]);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        private void InvisibleButtons()
        {
            btnCntrls.Visible = false;
            pnlView.Visible = true;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";
        }

        #endregion

        #region "Set Values to OnBehalfof"

        private void SetValuestoOnBehalfof(SPListItem lstDatas)
        {
            SPFieldUserValue user = new SPFieldUserValue(SPContext.Current.Web, lstDatas["SubmittedFor"].ToString());
            //setPeopleEditors(user, pplReqUser);

            pplReqUser.Visible = false;
            txtReqUser.Visible = true; txtReqUser.ReadOnly = true;
            txtReqUser.Text = user.LookupValue.ToString();
            txtReqEmpId.Text = Convert.ToString(lstDatas["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(lstDatas["Division"]);
            txtReqDept.Text = Convert.ToString(lstDatas["Department"]);
            txtReqDesignation.Text = Convert.ToString(lstDatas["Designation"]);
            txtReqMobileNo.Text = Convert.ToString(lstDatas["MobileNo"]);
            txtReqMobileNo.Enabled = false;
        }

        #endregion

        protected void ddlInstal_SelectedIndexChanged(object sender, EventArgs e)
        {

            double adv = Convert.ToDouble(txtAdvance.Text);
            double insTime = Convert.ToDouble(txtInstalment.Text);
            double pm = adv / insTime;
            txtDeduction.Text = Convert.ToString(Math.Round(pm, 2));
            dtStDate.ClearSelection();
            dtStDate.SelectedDate = DateTime.Today.AddMonths(1);


            dtEndDate.ClearSelection();
            if (insTime == 1)
            {
                dtEndDate.SelectedDate = DateTime.Today.AddMonths(1);
            }
            else
            {
                dtEndDate.SelectedDate = DateTime.Today.AddMonths(Convert.ToInt32(insTime));
            }

            double os = 0;
            if (!string.IsNullOrEmpty(txtOS.Text))
                os = Convert.ToDouble(txtAdvance.Text) + Convert.ToDouble(txtOS.Text);
            else
                os = Convert.ToDouble(txtAdvance.Text);

            txtTotOS.Text = Convert.ToString(os);

        }

        //private void InstalTime()
        //{
        //    for (int i = 0; i <= 60; i++)
        //    {
        //        ddlInstal.Items.Add(i.ToString());
        //    }

        //    //ddlInstal.DataSource = Enumerable.Range(0, 60);
        //    //ddlInstal.DataBind();
        //}


        public void rdBtn_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rdBtn.SelectedIndex == 0)
                pnlReqEmpInf.Visible = false;
            else
                pnlReqEmpInf.Visible = true;
        }

        /// <summary>
        /// For On behalf of section
        /// </summary>
        private void ClearControls()
        {
            if (rdBtn.SelectedIndex == 0)
                pplReqUser.Entities.Clear();

            txtReqEmpId.Text = ""; txtReqDivision.Text = ""; txtReqDept.Text = ""; txtReqDesignation.Text = ""; txtReqMobileNo.Text = "";
            dtDOE.ClearSelection(); txtBasicSalary.Text = "";
        }

        /// <summary>
        /// Get requested employee information
        /// </summary>

        #region "Get Requested Employee Information"

        private void GetReqEmpInfo()
        {
            if (rdBtn.SelectedIndex == 1 && pplReqUser.Accounts.Count > 0)
            {
                obj.GetCurrentUserDetails(pplReqUser.CommaSeparatedAccounts, txtReqEmpId, txtReqDivision, txtReqDept, txtReqDesignation, txtReqMobileNo);
                GetPersonnelActionForm();
            }
        }


        private void GetPersonnelActionForm()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                string empId = string.Empty;
                if (rdBtn.SelectedIndex == 0)
                {
                    Label lblEmpID = userInfo.FindControl("lblEmpID") as Label;
                    if (lblEmpID.Text != null)
                    {
                        UserProfile up = obj.GetUserInfo(SPContext.Current.Web.CurrentUser.LoginName);
                        empId = (string)up["EmployeeID"].Value;
                    }
                    else
                    {
                        empId = lblEmpID.Text;
                    }
                }
                else
                {
                    empId = txtReqEmpId.Text;
                }
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        qry = new SPQuery();
                        camlQry = "<Where><Eq><FieldRef Name=\"EmployeeID\" /><Value Type=\"Text\">" + empId + "</Value></Eq></Where>";
                        qry.Query = camlQry;
                        oItem = obj.GetSPListItem(SiteURL, "Personnel Action Forms", qry);
                        if (oItem != null)
                        {
                            dtDOE.SelectedDate = Convert.ToDateTime(oItem["DOB"]);
                            qry = new SPQuery();
                            camlQry = "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + Convert.ToString(oItem["Title"]) + "</Value>" +
                                "</Eq><Eq><FieldRef Name=\"Specification\" /><Value Type=\"Text\">Basic Salary</Value></Eq></And></Where>";
                            qry.Query = camlQry;
                            oItem = obj.GetSPListItem(SiteURL, "Personnel Action Details", qry);
                            if (oItem != null)
                            {
                                txtBasicSalary.Text = Convert.ToString(oItem["Present"]);
                            }
                        }
                        else
                        { 
                         
                        }

                    }
                }
                GetOutstanding(empId);
            });

        }

        #endregion


        protected void txtAdvance_TextChanged(object sender, EventArgs e)
        {

        }


        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (Request.QueryString["Mode"] == "Edit")
                {
                    string formID = null;
                    string refNo = Request.QueryString["RefID"];
                    string taskItemID = Request.QueryString["TaskItemID"];
                    string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                    if (GetSendbackStatus())
                    {
                        if (CheckServersideValidation())
                        {
                            SPLongOperation lop = new SPLongOperation(this.Page);
                            lop.LeadingHTML = "<DIV><H4>HR Request form approval is in progress</H4></DIV>";
                            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                            lop.Begin();
                            obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                                TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, null);
                            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                        }
                    }
                    else
                    {
                        lblError.Text = "Can't be send back. User is not available";
                    }
                }
                else if (Request.QueryString["Mode"] == "New")
                {
                    SaveFormDetails();
                    ClientScript.RegisterClientScriptBlock(GetType(), "Record Saved", "window.close", true);
                }
            }
        }


        /// <summary>
        /// check the user availability
        /// </summary>
        /// <returns></returns>

        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]),
                    lblSalAdvReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }

        /// <summary>
        /// Save Form details 
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>
        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Salary Advance form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblSalAdvReqNo, SiteURL);
                AdvRequestNo = Convert.ToString(lblSalAdvReqNo.Text).Trim();
                if (AdvRequestNo.Contains(DateTime.Now.Year.ToString()))
                {
                    lop.Begin();

                    lstGuid = obj.AddSalAdv_RequestItems(SiteURL, MainLstName, TaskLstName, CmntsLstName, rdBtn.SelectedIndex, AttLibName, upfile, WorkflowConfigList, pplcnt,
                        lblSalAdvReqNo.Text, Convert.ToString(dtpDate.SelectedDate), CurrentUser.ToLower(), EmpID.Text, Division.Text, Department.Text, Designation.Text,
                        MobNo.Text, pplReqUser.CommaSeparatedAccounts.ToLower(), txtReqEmpId.Text, txtReqDivision.Text, txtReqDept.Text, txtReqDesignation.Text,
                        txtReqMobileNo.Text, Convert.ToString(dtDOE.SelectedDate), txtBasicSalary.Text, txtAdvance.Text, txtInstalment.Text, txtDeduction.Text,
                        Convert.ToString(dtStDate.SelectedDate), Convert.ToString(dtEndDate.SelectedDate), txtOS.Text, txtTotOS.Text, TxtComments.Text);

                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
                else
                {
                    lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                }
            });
        }


        protected void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Salary Advance form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, submittedfor))
                            SetOutStanding();
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {

                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>HSalary Advance form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();
                    if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                        TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true, 2, submittedfor))
                        SetOutStanding();
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Salary Advance form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();

                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {
                    Label lblFormID = userInfo.FindControl("lblFormID") as Label;
                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, lblFormID.Text.ToString().ToLower(), refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, lblFormID.Text.ToString().ToLower(), upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lblFormID.Text.ToString().ToLower(), CurrentUser, TxtComments.Text, 0);

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: HR Request form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }


        private void SetOutStanding()
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                string referenceNo = lblSalAdvReqNo.Text;
                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(AdvanceDetails);
                        if (oList != null)
                        {
                            SPQuery oEmptyQuery = new SPQuery();
                            oEmptyQuery.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Eq></Where>";
                            SPListItemCollection oItemColl = oList.GetItems(oEmptyQuery);
                            SPListItem oItem = oItemColl.Add();
                            oItem["Title"] = referenceNo;
                            oItem["User"] = fldSubmittedFor;
                            oItem["AdvanceAmount"] = Convert.ToDouble(txtAdvance.Text);
                            oItem["OutstandingAmount"] = Convert.ToDouble(txtAdvance.Text);
                            if (rdBtn.SelectedIndex == 0)
                                oItem["EmployeeID"] = Convert.ToString(EmpID);
                            else
                                oItem["EmployeeID"] = Convert.ToString(txtReqEmpId.Text);
                            oWeb.AllowUnsafeUpdates = true;
                            oItem.Update();
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });

        }

        private void GetOutstanding(string empID)
        {
            try
            {
                string user = string.Empty;

                double os = 0;
                if (rdBtn.SelectedIndex == 0)
                {
                    user = SPContext.Current.Web.CurrentUser.LoginName;
                }
                else
                {
                    PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];
                    user = pe.DisplayText;
                }
                camlQry = "<Where><And><Eq><FieldRef Name=\"User\" /><Value Type=\"User\">" + user + "</Value></Eq><Eq><FieldRef Name=\"EmployeeID\" />" +
                    "<Value Type=\"Text\">" + empID + "</Value></Eq></And></Where>";
                oItemColl = obj.GetSPListItems(SiteURL, AdvanceDetails, camlQry);

                if (oItemColl != null)
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem item in oItemColl)
                        {
                            os = os + Convert.ToDouble(item["OutstandingAmount"]);
                            txtOS.Text = Convert.ToString(os);
                        }
                    }
                    else { txtOS.Text = ""; }
                }
                else
                { txtOS.Text = ""; }
            }
            catch (Exception)
            {

            }
        }

    }
}
